<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>旅行社会员管理系统</title>
    <style>
        body { font-family: '微软雅黑', sans-serif; margin: 0; padding: 20px; background: #f0f2f5; }
        .container { max-width: 1200px; margin: 0 auto; }
        .hidden { display: none; }
        .login-box { width: 300px; margin: 100px auto; padding: 20px; background: white; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .nav-bar { background: #1890ff; padding: 12px; border-radius: 6px; margin-bottom: 20px; display: flex; flex-wrap: wrap; gap: 5px; }
        .nav-button { background: #fff; color: #1890ff; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer; flex: 1 1 auto; }
        .form-section { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); margin-bottom: 20px; }
        .form-row { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; color: #666; }
        input, select, textarea { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }
        .perm-item input[type="checkbox"] {
            padding: 0;
            margin: 0;
        }
        .required::after { content: "*"; color: red; margin-left: 3px; }
        .result-item { border: 1px solid #eee; border-radius: 6px; padding: 15px; margin-bottom: 10px; background: white; }
        .info-line { display: flex; gap: 15px; align-items: center; margin-bottom: 8px; }
        .detail-info { color: #666; font-size: 0.9em; }
        .modal-mask { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 999; }
        .search-box { display: flex; gap: 10px; margin-bottom: 20px; }
        .log-item {
            padding: 8px 12px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
        }
        .log-item.header {
            font-weight: bold;
            background: #f8f9fa;
        }

        /* 权限项样式修正 */
        .perm-container {
            display: flex;
            flex-direction: column;
            gap: 12px;
            margin-left: 10px;
        }
        .perm-item {
            display: flex;
            align-items: center;
            gap: 4px;
        }
        .perm-check {
            width: 16px;
            height: 16px;
            margin: 0 6px 0 0;
            vertical-align: middle;
        }

        /* 账户弹窗样式修正 */
        #accountModal {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            border-radius: 8px;
            width: 60vw;
            min-width: 300px;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0,0,0,0.2);
            z-index: 1000;
        }

        @media (max-width: 768px) { 
            #accountModal {
                width: 80vw !important;
                height: auto !important;
                min-width: unset !important;
                min-height: unset !important;
            }
        }

        /* 标签对齐优化 */
        #accountModal .form-row > label {
            min-width: 80px;
            display: inline-block;
            flex-shrink: 0;
            vertical-align: top;
            padding-top: 8px;
        }
    </style>
</head>
<body>
    <!-- 登录界面 -->
    <div id="loginSection" class="login-box">
        <h2>用户登录</h2>
        <div class="form-row">
            <label>用户名</label>
            <input type="text" id="username">
        </div>
        <div class="form-row">
            <label>密码</label>
            <input type="password" id="password">
        </div>
        <button onclick="login()">登录</button>
    </div>

    <!-- 主界面 -->
    <div id="mainSection" class="hidden container">
        <div class="nav-bar">
            <button class="nav-button" onclick="showSection('input')">数据录入</button>
            <button class="nav-button" onclick="showSection('query')">数据查询</button>
            <button class="nav-button" onclick="showSection('batch')">批量操作</button>
            <button class="nav-button" onclick="showSection('overview')">总体查询</button>
            <button class="nav-button" onclick="showSection('account')" id="adminButton">账户管理</button>
            <button class="nav-button" onclick="showSection('log')">工作日志</button>
            <button class="nav-button" onclick="showSection('notice')">公司公告</button>
        </div>

        <!-- 数据录入 -->
        <div id="inputSection" class="form-section">
            <h2>会员信息录入</h2>
            <form id="inputForm" onsubmit="return submitForm()">
                <div class="form-row"><label class="required">姓名</label><input type="text" id="name" required></div>
                <div class="form-row"><label class="required">身份证号</label><input type="text" id="idCard" pattern="\d{17}[\dX]" required></div>
                <div class="form-row"><label class="required">电话</label><input type="tel" id="phone" pattern="1[3-9]\d{9}" required></div>
                <div class="form-row"><label class="required">年龄</label><input type="number" id="age" min="1" max="120" required></div>
                <div class="form-row"><label class="required">所在地</label><input type="text" id="location" required></div>
                <div class="form-row"><label>工作单位</label><input type="text" id="company"></div>
                <div class="form-row"><label>职务</label><input type="text" id="position"></div>
                <div class="form-row">
                    <label class="required">性别</label>
                    <select id="gender" required>
                        <option value="">请选择</option>
                        <option>男</option>
                        <option>女</option>
                    </select>
                </div>
                <div class="form-row"><label class="required">业务员</label><input type="text" id="salesman" required></div>
                <div class="form-row"><label>备注</label><textarea id="remark"></textarea></div>
                <div class="form-row"><label class="required">会员等级</label>
                    <select id="level" required>
                        <option value="">请选择</option>
                        <option>1</option><option>2</option><option>3</option><option>4</option><option>5</option>
                    </select>
                </div>
                <div class="form-row">
                    <label class="required">优待证</label>
                    <label><input type="radio" name="privilege" value="是" required> 是</label>
                    <label><input type="radio" name="privilege" value="否"> 否</label>
                </div>
                <div class="form-row"><label>积分</label><input type="number" id="integral"></div>
                <div class="form-row"><label>订单信息</label><textarea id="order" maxlength="500"></textarea></div>
                <div class="form-row"><label>消费记录</label><textarea id="consumption"></textarea></div>
                <button type="submit">提交</button>
            </form>
        </div>

        <!-- 数据查询 -->
        <div id="querySection" class="hidden form-section">
            <h2>数据查询</h2>
            <div class="search-box">
                <input type="text" id="searchInput" placeholder="输入姓名/电话/身份证/单位名称/业务员">
                <select id="searchType">
                    <option value="all">全部</option>
                    <option value="retire">退休人员</option>
                    <option value="privilege">有优待证</option>
                </select>
                <button onclick="searchData()">查询</button>
            </div>
            <div id="queryResults"></div>
        </div>

        <!-- 批量操作 -->
        <div id="batchSection" class="hidden form-section">
            <h2>批量操作</h2>
            <div class="batch-box">
                <div><input type="file" id="importFile" accept=".txt"><button onclick="importData()">导入数据</button></div>
                <button onclick="exportData()">导出数据</button>
            </div>
        </div>

        <!-- 总体查询 -->
        <div id="overviewSection" class="hidden form-section">
            <h2>总体查询</h2>
            <div class="filter-box">
                <div><label>年龄范围：</label><input type="number" id="minAge" placeholder="最小年龄">-<input type="number" id="maxAge" placeholder="最大年龄"></div>
                <div><label>职业：</label>
                    <select id="filterOccupation">
                        <option value="">全部</option>
                        <option>退休</option><option>在职</option><option>自由职业</option><option>学生</option>
                    </select>
                </div>
                <div><label>等级：</label>
                    <select id="filterLevel">
                        <option value="">全部</option>
                        <option>1</option><option>2</option><option>3</option><option>4</option><option>5</option>
                    </select>
                </div>
                <div><label>优待证：</label>
                    <select id="filterPrivilege">
                        <option value="">全部</option>
                        <option>是</option><option>否</option>
                    </select>
                </div>
                <button onclick="filterData()">筛选</button>
            </div>
            <div id="overviewResults"></div>
        </div>

        <!-- 账户管理 -->
        <div id="accountSection" class="hidden form-section">
            <h2>账户管理</h2>
            <div class="form-row"><button onclick="showAddAccount()">新增账户</button></div>
            <div id="accountList"></div>

            <!-- 账户弹窗 -->
            <div id="accountModal" class="hidden">
                <h3>账户设置</h3>
                <div class="form-row">
                    <label class="required">用户名</label>
                    <input type="text" id="newUsername" required>
                </div>
                <div class="form-row">
                    <label class="required">密码</label>
                    <input type="password" id="newPassword" required>
                </div>
                <div class="form-row">
                    <label class="required">姓名</label>
                    <input type="text" id="newRealName" required>
                </div>
                <div class="form-row">
                    <label class="required">身份证号</label>
                    <input type="text" id="newIdCard" pattern="\d{17}[\dX]" required>
                </div>
                <div class="form-row">
                    <label class="required">联系电话</label>
                    <input type="tel" id="newPhone" pattern="1[3-9]\d{9}" required>
                </div>
                <div class="form-row">
                    <label class="required">部门</label>
                    <select id="newDepartment" required>
                        <option value="">请选择</option>
                        <option>销售部</option>
                        <option>客服部</option>
                        <option>运营部</option>
                        <option>财务部</option>
                    </select>
                </div>
                <div class="form-row">
                    <label class="required">工作岗位</label>
                    <input type="text" id="newPosition" required>
                </div>
                <div class="form-row">
                    <label class="required">职务</label>
                    <input type="text" id="newJobTitle" required>
                </div>
                <div class="form-row">
                    <label>角色</label>
                    <select id="newRole">
                        <option>admin</option>
                        <option>总经理</option>
                        <option>副总经理</option>
                        <option>经理</option>
                        <option>副经理</option>
                        <option>组长</option>
                        <option>员工</option>
                    </select>
                </div>
                <div class="form-row">
                    <label>权限配置</label>
                    <div class="perm-container">
                        <div class="perm-item">
                            <input type="checkbox" class="perm-check" data-perm="manageAccounts">
                            <span>账户管理</span>
                        </div>
                        <div class="perm-item">
                            <input type="checkbox" class="perm-check" data-perm="batchOperate">
                            <span>批量操作</span>
                        </div>
                        <div class="perm-item">
                            <input type="checkbox" class="perm-check" data-perm="editData">
                            <span>数据编辑</span>
                        </div>
                        <div class="perm-item">
                            <input type="checkbox" class="perm-check" data-perm="deleteData">
                            <span>数据删除</span>
                        </div>
                    </div>
                </div>
                <div class="form-row">
                    <button onclick="saveAccount()">保存</button>
                    <button onclick="closeAccountModal()">取消</button>
                </div>
            </div>
        </div>

        <!-- 登录记录 -->
        <div id="logSection" class="hidden form-section">
            <h2>登录记录</h2>
            <div id="logList">
                <div class="log-item header"><span>账户</span><span>登录时间</span></div>
            </div>
        </div>

        <!-- 公司公告 -->
        <div id="noticeSection" class="hidden form-section">
            <h2>公司公告管理</h2>
            <div class="form-row">
                <label>特价旅游信息</label>
                <textarea id="discountInfo" rows="3"></textarea>
            </div>
            <div class="form-row">
                <label>积分兑换信息</label>
                <textarea id="pointsInfo" rows="3"></textarea>
            </div>
            <button onclick="saveNotice()">保存公告</button>
            <div id="noticeDisplay" style="margin-top:20px; padding:10px; background:#f8f9fa;"></div>
        </div>
    </div>

    <!-- 编辑弹窗 -->
    <div id="editModal" class="hidden" style="
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: white;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 0 10px rgba(0,0,0,0.2);
        z-index: 1000;
        max-width: 90vw;
        max-height: 90vh;
        min-width: 300px;
        overflow: auto;">
        <h3 style="margin: 0 0 15px 0;">编辑会员信息</h3>
        <div id="editForm" style="flex: 1;"></div>
        <div style="margin-top: auto; padding-top: 15px;">
            <button onclick="saveEdit()">保存</button>
            <button onclick="closeEdit()">取消</button>
        </div>
    </div>

    <script>
        // 存储初始化
        function initStorage() {
            if (!localStorage.loginLogs) {
                localStorage.loginLogs = JSON.stringify([]);
            }

            if (!localStorage.users) {
                const surnames = ['王','李','张','刘','陈','杨','赵','黄','周','吴'];
                const names = ['伟','芳','娜','敏','静','强','磊','军','杰','涛'];
                const testData = Array.from({length:10}, (_,i) => ({
                    id: Date.now() + i,
                    name: surnames[i % surnames.length] + names[i % names.length],
                    idCard: '110101' + (200000000000 + i).toString().slice(-11),
                    phone: '138' + (10000000 + i).toString().padStart(8, '0'),
                    age: Math.floor(Math.random() * 50 + 20),
                    location: ['北京','上海','广州','深圳'][i % 4],
                    occupation: ['退休','在职','自由职业','学生'][i % 4],
                    remark: i % 3 === 0 ? '特殊需求' : '',
                    level: (i % 5 + 1).toString(),
                    privilege: i % 2 ? '是' : '否',
                    integral: (i * 100).toString(),
                    order: 'ORD' + (1000 + i).toString(),
                    consumption: i % 2 ? '无记录' : '2023年消费' + (i + 1) + '次',
                    gender: ['男', '女'][i % 2],
                    company: ['公司A', '公司B'][i % 2],
                    salesman: ['销售员1', '销售员2'][i % 2],
                    createTime: new Date(Date.now() - Math.random() * 12 * 60 * 60 * 1000).toISOString()
                }));
                localStorage.users = JSON.stringify(testData);
            }

            if (!localStorage.accounts) {
                localStorage.accounts = JSON.stringify([{
                    username: 'admin',
                    password: 'admin123',
                    role: 'admin',
                    realName: '管理员',
                    idCard: '11010119800101001X',
                    phone: '13800000000',
                    department: '管理部',
                    position: '系统管理员',
                    jobTitle: '超级管理员',
                    permissions: {
                        manageAccounts: true,
                        batchOperate: true,
                        editData: true,
                        deleteData: true
                    }
                }]);
            }

            if (!localStorage.noticeData) {
                localStorage.noticeData = JSON.stringify({
                    discount: "暑期国内游立减500元",
                    points: "100积分兑换旅行收纳包"
                });
            }
        }

        // 登录系统
        function login() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            const accounts = JSON.parse(localStorage.accounts || '[]');
            const valid = accounts.some(a => a.username === username && a.password === password);
            
            if(valid) {
                document.getElementById('loginSection').classList.add('hidden');
                document.getElementById('mainSection').classList.remove('hidden');
                recordLogin(username);
                checkAdmin();
                checkPermissions();
                showNotice();
                showSection('input');
            } else {
                alert('登录失败');
            }
        }

        // 权限检查
        function checkPermissions() {
            const currentUser = document.getElementById('username').value;
            const accounts = JSON.parse(localStorage.accounts);
            const currentAccount = accounts.find(a => a.username === currentUser) || {};
            
            const isAdmin = currentAccount.role === 'admin';
            const permissions = isAdmin ? {
                manageAccounts: true,
                batchOperate: true,
                editData: true,
                deleteData: true
            } : (currentAccount.permissions || {});

            document.querySelectorAll('.nav-button').forEach(btn => {
                const btnText = btn.textContent;
                if(btnText === '账户管理') btn.hidden = !permissions.manageAccounts;
                if(btnText === '批量操作') btn.hidden = !permissions.batchOperate;
            });

            document.querySelectorAll('#queryResults button, #overviewResults button').forEach(btn => {
                if(btn.textContent === '编辑') btn.disabled = !permissions.editData;
                if(btn.textContent === '删除') btn.disabled = !permissions.deleteData;
            });
        }

        // 显示功能区块
        function showSection(sectionId) {
            document.querySelectorAll('.form-section').forEach(el => el.classList.add('hidden'));
            document.getElementById(sectionId + 'Section').classList.remove('hidden');
            
            if(sectionId === 'account') {
               refreshAccountList(); 
            } else if(sectionId === 'log') {  
                showLoginLogs();
            } else if(sectionId === 'notice') { 
                showNotice();
            }
        }

        // 数据录入
        function submitForm() {
            const currentUser = document.getElementById('username').value;
            const accounts = JSON.parse(localStorage.accounts);
            const userRole = accounts.find(a => a.username === currentUser)?.role;
            
            if(!['正式员工','前台组长','门面经理','admin'].includes(userRole)) {
                alert('无录入权限');
                return false;
            }

            const formData = {
                id: Date.now(),
                name: document.getElementById('name').value,
                idCard: document.getElementById('idCard').value,
                phone: document.getElementById('phone').value,
                age: document.getElementById('age').value,
                location: document.getElementById('location').value,
                company: document.getElementById('company').value,
                position: document.getElementById('position').value,
                gender: document.getElementById('gender').value,
                salesman: document.getElementById('salesman').value,
                remark: document.getElementById('remark').value,
                level: document.getElementById('level').value,
                privilege: document.querySelector('input[name="privilege"]:checked').value,
                integral: document.getElementById('integral').value || '0',
                order: document.getElementById('order').value || '',
                consumption: document.getElementById('consumption').value || '',
                createTime: new Date().toISOString()
            };
            
            const users = JSON.parse(localStorage.users);
            users.push(formData);
            localStorage.users = JSON.stringify(users);
            alert('录入成功');
            document.getElementById('inputForm').reset();
            return false;
        }

        // 数据查询
        function searchData() {
            const searchText = document.getElementById('searchInput').value.toLowerCase();
            const searchType = document.getElementById('searchType').value;
            const users = JSON.parse(localStorage.users);
            
            const results = users.filter(user => {
                const matchText = 
                                 (user.name ?? '').toLowerCase().includes(searchText) || 
                                 (user.phone ?? '').includes(searchText) || 
                                 (user.idCard ?? '').includes(searchText) ||
                                 (user.company ?? '').toLowerCase().includes(searchText) ||
                                 (user.salesman ?? '').toLowerCase().includes(searchText);
                
                const matchType = {
                    all: true,
                    retire: user.occupation === '退休',
                    privilege: user.privilege === '是'
                }[searchType];
                
                return matchText && matchType;
            });
            
            displayResults(results, 'queryResults');
        }

        // 显示结果
        function displayResults(data, containerId) {
            const template = `
                <div class="result-item">
                    <div class="info-line">
                        <span>姓名：{{name}}</span>
                        <span>电话：{{phone}}</span>
                        <span>等级：{{level}}</span>
                        <span>积分：{{integral}}</span>
                        <button onclick="editUser('{{id}}')">编辑</button>
                        <button onclick="deleteUser('{{id}}')">删除</button>
                    </div>
                    <div class="detail-info">
                        <div>身份证：{{idCard}}</div>
                        <div>年龄：{{age}} 所在地：{{location}}</div>
                        <div>性别：{{gender}}</div>
                        <div>工作单位：{{company}}</div>
                        <div>职务：{{position}}</div>
                        <div>业务员：{{salesman}}</div>
                        <div>订单信息：{{order}}</div>
                        <div>消费记录：{{consumption}}</div>
                        <div>备注：{{remark}}</div>
                        <div>录入时间：{{createTime}}</div>
                    </div>
                </div>
            `;
            
            const container = document.getElementById(containerId);
            container.innerHTML = '';
            
            data.forEach(user => {
                const processedUser = {
                    ...user,
                    gender: user.gender || '未填写',
                    company: user.company || '未填写',
                    position: user.position || '未填写',
                    order: user.order || '无',
                    consumption: user.consumption || '无',
                    remark: user.remark || '无'
                };
                
                let html = template.replace(/\{\{(\w+)\}\}/g, (_, key) => user[key] || '');
                html = html.replace(/{{id}}/g, user.id);
                container.insertAdjacentHTML('beforeend', html);
            });
        }

        // 删除用户
        function deleteUser(id) {
            const currentUser = document.getElementById('username').value;
            const accounts = JSON.parse(localStorage.accounts);
            const userRole = accounts.find(a => a.username === currentUser)?.role;
            
            if(userRole !== 'admin' && userRole !== '门面经理') {
                alert('无删除权限');
                return;
            }

            if(confirm('确定删除该会员？')) {
                let users = JSON.parse(localStorage.users);
                users = users.filter(u => u.id != id);
                localStorage.users = JSON.stringify(users);
                searchData();
            }
        }

        // 编辑用户
        let currentEditId = null;
        function editUser(id) {
            const users = JSON.parse(localStorage.users);
            const user = users.find(u => u.id == id);
            currentEditId = id;
            
            const originalConsumption = user.consumption || '';
            document.getElementById('editForm').innerHTML = document.getElementById('inputForm').innerHTML;
            const form = document.getElementById('editForm');

            form.querySelector('#name').value = user.name;
            form.querySelector('#idCard').value = user.idCard;
            form.querySelector('#phone').value = user.phone;
            form.querySelector('#age').value = user.age;
            form.querySelector('#location').value = user.location;
            form.querySelector('#position').value = user.position || '';
            form.querySelector('#remark').value = user.remark;
            form.querySelector('#level').value = user.level;
            form.querySelector(`input[name="privilege"][value="${user.privilege}"]`).checked = true;
            form.querySelector('#integral').value = user.integral || '';
            form.querySelector('#order').value = user.order || '';
            form.querySelector('#company').value = user.company || '';
            form.querySelector('#gender').value = user.gender || '';
            form.querySelector('#salesman').value = user.salesman || '';
            form.querySelector('#consumption').value = originalConsumption;
            
            document.getElementById('editModal').classList.remove('hidden');
        }

        // 保存编辑
        function saveEdit() {
            const currentUser = document.getElementById('username').value;
            const accounts = JSON.parse(localStorage.accounts);
            const userRole = accounts.find(a => a.username === currentUser)?.role;
            
            if(!['前台组长','门面经理','admin'].includes(userRole)) {
                alert('无修改权限');
                return;
            }

            const users = JSON.parse(localStorage.users);
            const index = users.findIndex(u => u.id == currentEditId);
            
            users[index] = {
                ...users[index],
                name: document.querySelector('#editForm #name').value,
                idCard: document.querySelector('#editForm #idCard').value,
                phone: document.querySelector('#editForm #phone').value,
                age: document.querySelector('#editForm #age').value,
                location: document.querySelector('#editForm #location').value,
                remark: document.querySelector('#editForm #remark').value,
                level: document.querySelector('#editForm #level').value,
                privilege: document.querySelector('#editForm input[name="privilege"]:checked').value,
                integral: document.querySelector('#editForm #integral').value || '0',
                order: document.querySelector('#editForm #order').value || '',
                consumption: document.querySelector('#editForm #consumption').value || '',
                company: document.querySelector('#editForm #company').value || '',
                position: document.querySelector('#editForm #position').value || '',
                gender: document.querySelector('#editForm #gender').value || '',
                salesman: document.querySelector('#editForm #salesman').value || ''
            };
            
            localStorage.users = JSON.stringify(users);
            closeEdit();
            searchData();
        }

        function closeEdit() {
            document.getElementById('editModal').classList.add('hidden');
        }

        // 批量导出
        function exportData() {
            const users = JSON.parse(localStorage.users);
            const fieldLabels = {
                "名字": "name",
                "身份证": "idCard",
                "电话": "phone",
                "年龄": "age",
                "所在地": "location",
                "职业": "occupation",
                "备注": "remark",
                "等级": "level",
                "优待证": "privilege",
                "积分": "integral",
                "订单": "order",
                "消费记录": "consumption",
                "创建时间": "createTime"
            };

            const text = users.map(user => {
                return Object.entries(fieldLabels)
                    .map(([label, key]) => `${label}: ${user[key] || '无'}`)
                    .join('\n') + '\n' + '-'.repeat(30);
            }).join('\n');

            const blob = new Blob([text], { type: 'text/plain' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `members_${new Date().toISOString().slice(0,10)}.txt`;
            a.click();
        }

        // 批量导入
        function importData() {
            const file = document.getElementById('importFile').files[0];
            if(!file) return alert('请选择文件');
            
            const reader = new FileReader();
            reader.onload = function(e) {
                const text = e.target.result;
                const users = [];
                
                const userBlocks = text.split('\n' + '-'.repeat(30) + '\n');
                
                userBlocks.forEach(block => {
                    if(!block.trim()) return;
                    
                    const user = {};
                    const lines = block.split('\n').filter(l => l.trim());
                    
                    lines.forEach(line => {
                        const match = line.match(/(.+):\s(.+)/);
                        if(match) {
                            const label = match[1].trim();
                            const value = match[2].trim();
                            
                            const fieldMap = {
                                '名字': 'name',
                                '身份证': 'idCard',
                                '电话': 'phone',
                                '年龄': 'age',
                                '所在地': 'location',
                                '职业': 'occupation',
                                '备注': 'remark',
                                '等级': 'level',
                                '优待证': 'privilege',
                                '积分': 'integral',
                                '订单': 'order',
                                '消费记录': 'consumption',
                                '性别': 'gender',
                                '工作单位': 'company',
                                '职务': 'position',
                                '业务员': 'salesman'
                            };
                            
                            if(fieldMap[label]) {
                                user[fieldMap[label]] = value === '无' ? '' : value;
                            }
                        }
                    });
                    
                    if(Object.keys(user).length > 0) {
                        users.push({
                            ...user,
                            id: Date.now() + Math.random(),
                            createTime: new Date().toISOString(),
                            age: parseInt(user.age) || 0,
                            integral: parseInt(user.integral) || 0
                        });
                    }
                });

                const existing = JSON.parse(localStorage.users);
                localStorage.users = JSON.stringify([...existing, ...users]);
                alert(`成功导入 ${users.length} 条数据`);
                if(document.getElementById('querySection').classList.contains('hidden') === false) {
                    searchData();
                }
            };
            reader.readAsText(file);
        }

        // 总体查询筛选
        function filterData() {
            const users = JSON.parse(localStorage.users);
            const minAge = parseInt(document.getElementById('minAge').value) || 0;
            const maxAge = parseInt(document.getElementById('maxAge').value) || 120;
            const occupation = document.getElementById('filterOccupation').value;
            const level = document.getElementById('filterLevel').value;
            const privilege = document.getElementById('filterPrivilege').value;
            
            const results = users.filter(user => 
                user.age >= minAge &&
                user.age <= maxAge &&
                (occupation ? user.occupation === occupation : true) &&
                (level ? user.level === level : true) &&
                (privilege ? user.privilege === privilege : true)
            );
            
            displayResults(results, 'overviewResults');
        }

        // 账户管理
        function showAddAccount() {
            document.getElementById('accountModal').classList.remove('hidden');
            document.getElementById('newUsername').disabled = false;
            document.querySelectorAll('#accountModal input, #accountModal select').forEach(el => {
                if (el.type !== 'button') el.value = '';
            });
        }

        // 保存账户
        function saveAccount() {
            const accounts = JSON.parse(localStorage.accounts);
            const isEditMode = !!currentEditAccount;

            const newAccount = {
                username: document.getElementById('newUsername').value,
                password: document.getElementById('newPassword').value,
                role: document.getElementById('newRole').value,
                realName: document.getElementById('newRealName').value,
                idCard: document.getElementById('newIdCard').value,
                phone: document.getElementById('newPhone').value,
                department: document.getElementById('newDepartment').value,
                position: document.getElementById('newPosition').value,
                jobTitle: document.getElementById('newJobTitle').value,
                permissions: {
                    manageAccounts: document.querySelector('[data-perm="manageAccounts"]').checked,
                    batchOperate: document.querySelector('[data-perm="batchOperate"]').checked,
                    editData: document.querySelector('[data-perm="editData"]').checked,
                    deleteData: document.querySelector('[data-perm="deleteData"]').checked
                }
            };

            if (Object.values(newAccount).some(v => !v)) {
                alert('请填写所有必填项');
                return;
            }

            if (isEditMode) {
                const index = accounts.findIndex(a => a.username === currentEditAccount);
                if (index !== -1) {
                    accounts[index] = newAccount;
                } 
            } else {
                if (accounts.some(a => a.username === newAccount.username)) {
                    alert('用户名已存在');
                    return;
                }
                accounts.push(newAccount);
            }
            
            localStorage.accounts = JSON.stringify(accounts);
            closeAccountModal();
            refreshAccountList();
            currentEditAccount = null;
        }

        function refreshAccountList() {
            const accounts = JSON.parse(localStorage.accounts);
            const list = document.getElementById('accountList');
            list.innerHTML = '';
            
            accounts.forEach(acc => {
                const div = document.createElement('div');
                div.className = 'account-item';
                div.innerHTML = `
                    <div class="info-line">
                        <span>${acc.username}</span>
                        <span>角色：${acc.role}</span>
                        <span>部门：${acc.department || '未设置'}</span>
                        <span>职务：${acc.jobTitle || '未设置'}</span>
                        ${acc.role !== 'admin' ? `
                         <button onclick="editAccount('${acc.username}')">编辑</button> 
                         <button onclick="deleteAccount('${acc.username}')">删除</button>
    ` : ''}
                    </div>
                    <div class="detail-info">
                        <div>姓名：${acc.realName || '未设置'}</div>
                        <div>身份证：${acc.idCard || '未设置'}</div>
                        <div>电话：${acc.phone || '未设置'}</div>
                        <div>岗位：${acc.position || '未设置'}</div>
                    </div>
                `;
                list.appendChild(div);
            });
        }

        function deleteAccount(username) {
            if(confirm(`确定删除账户 ${username}？`)) {
                let accounts = JSON.parse(localStorage.accounts);
                accounts = accounts.filter(a => a.username !== username);
                localStorage.accounts = JSON.stringify(accounts);
                refreshAccountList();
            }
        }

        let currentEditAccount = null;
        function editAccount(username) {
            const accounts = JSON.parse(localStorage.accounts);
            const account = accounts.find(a => a.username === username);
            currentEditAccount = username;

            document.getElementById('newUsername').value = account.username;
            document.getElementById('newPassword').value = account.password;
            document.getElementById('newRole').value = account.role;
            document.getElementById('newRealName').value = account.realName || '';
            document.getElementById('newIdCard').value = account.idCard || '';
            document.getElementById('newPhone').value = account.phone || '';
            document.getElementById('newDepartment').value = account.department || '';
            document.getElementById('newPosition').value = account.position || '';
            document.getElementById('newJobTitle').value = account.jobTitle || '';
            document.querySelector('[data-perm="manageAccounts"]').checked = account.permissions?.manageAccounts || false;
            document.querySelector('[data-perm="batchOperate"]').checked = account.permissions?.batchOperate || false;
            document.querySelector('[data-perm="editData"]').checked = account.permissions?.editData || false;
            document.querySelector('[data-perm="deleteData"]').checked = account.permissions?.deleteData || false;
            document.getElementById('accountModal').classList.remove('hidden');
            document.getElementById('newUsername').disabled = true;
        }

        function closeAccountModal() {
            document.getElementById('accountModal').classList.add('hidden');
            document.getElementById('newUsername').disabled = false;
            document.querySelectorAll('#accountModal input, #accountModal select').forEach(el => {
                if (el.type !== 'button') el.value = '';
            });
            currentEditAccount = null;
        }

        // 登录记录
        function recordLogin(username) {
            const logs = JSON.parse(localStorage.loginLogs || '[]');
            logs.push({
                username: username,
                time: new Date().toISOString()
            });
            localStorage.loginLogs = JSON.stringify(logs.slice(-50));
        }

        function showLoginLogs() {
            const logs = JSON.parse(localStorage.loginLogs || '[]');
            const list = document.getElementById('logList');
            list.innerHTML = '<div class="log-item header"><span>账户</span><span>登录时间</span></div>';
            
            logs.reverse().forEach(log => {
                const div = document.createElement('div');
                div.className = 'log-item';
                div.style.display = 'flex';
                div.style.justifyContent = 'space-between';
                div.innerHTML = `
                    <span>${log.username}</span>
                    <span>${new Date(log.time).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })}</span>
                `;
                list.appendChild(div);
            });
        }

        // 公告管理
        function saveNotice() {
            localStorage.setItem('noticeData', JSON.stringify({
                discount: document.getElementById('discountInfo').value,
                points: document.getElementById('pointsInfo').value
            }));
            showNotice();
            alert('公告保存成功');
        }

        function showNotice() {
            const notice = JSON.parse(localStorage.getItem('noticeData') || '{}');
            const noticeDisplay = document.getElementById('noticeDisplay');
            noticeDisplay.innerHTML = `
                <h4>当前公告</h4>
                <div><strong>特价旅游：</strong>${notice.discount || '无'}</div>
                <div><strong>积分兑换：</strong>${notice.points || '无'}</div>
            `;
        }

        // 权限检查
        function checkAdmin() {
            const currentUser = document.getElementById('username').value;
            const accounts = JSON.parse(localStorage.accounts);
            const isAdmin = accounts.some(a => a.username === currentUser && a.role === 'admin');
            document.getElementById('adminButton').classList.toggle('hidden', !isAdmin);
        }

        // 初始化
        initStorage();
        document.getElementById('adminButton').classList.add('hidden');
    </script>
</body>
</html>